import React from 'react';
import { Button, Checkbox } from 'antd';
import { WeaTools, WeaLocaleProvider, WeaTop, WeaDialog, WeaSearchGroup, WeaTable } from 'ecCom';

const isIE = WeaTools.ua.browser == 'IE';
const getLabel = WeaLocaleProvider.getLabel;

class WeaPlugin extends React.Component {
  constructor(props) {
    super(props);
    this.state = { loading: false, test: false, isCheck: false, data: {} };
  }

  componentWillMount() {
    const { display, visible } = this.props;
    if (display == 'page' || visible) {
      this.getPlugins();
    }
  }

  componentWillReceiveProps(nextProps) {
    const { visible } = nextProps;
    if (visible) {
      this.getPlugins();
    }
  }

  render() {
    const { display, visible } = this.props;
    const { loading, test = false, isCheck = false, data = {} } = this.state;
    const { plugins = [], otherPlugins = [] } = data;
    plugins.forEach((item) => {
      for (let it in item) {
        if (it == 'explain') {
          item[it] = item[it].replace('、报表控件', '');
        }
      }
    });

    let columns = [
      { key: 'index', title: getLabel(15486, '序号'), dataIndex: 'index', width: '10%' },
      { key: 'name', title: getLabel(195, '名称'), dataIndex: 'name', width: '20%' },
      { key: 'explain', title: getLabel(433, '描述'), dataIndex: 'explain', width: '35%' },
      { key: 'size', title: getLabel(2036, '大小'), dataIndex: 'size', width: '10%' },
      {
        key: 'status',
        title: getLabel(602, '状态'),
        dataIndex: 'status',
        width: '10%',
        render: (text, record) => this.getPluginStatus(record.progid),
      },
      {
        key: 'download',
        title: getLabel(22010, '下载并安装'),
        dataIndex: 'download',
        width: '15%',
        render: (text, record) => (
          <a href={record.url} target="_blank" style={{ color: '#00a9ff' }}>
            {getLabel(258, '下载')}
          </a>
        ),
      },
    ];

    let otherColumns = [
      { key: 'index', title: getLabel(15486, '序号'), dataIndex: 'index', width: '10%' },
      { key: 'name', title: getLabel(195, '名称'), dataIndex: 'name', width: '20%' },
      { key: 'explain', title: getLabel(433, '描述'), dataIndex: 'explain', width: '35%' },
      { key: 'size', title: getLabel(2036, '大小'), dataIndex: 'size', width: '10%' },
      { key: 'version', title: getLabel(567, '版本'), dataIndex: 'version', width: '10%' },
      {
        key: 'download',
        title: getLabel(22010, '下载并安装'),
        dataIndex: 'download',
        width: '15%',
        render: (text, record) => (
          <a href={record.url} target="_blank" style={{ color: '#00a9ff' }}>
            {getLabel(258, '下载')}
          </a>
        ),
      },
    ];

    let Content = (
      <div className="wea-plugin-body">
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@yjwf95`} title={getLabel(22005, '控件安装')} showGroup={true}>
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@gp811b`} columns={columns} dataSource={plugins} pagination={false} />
        </WeaSearchGroup>
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@fnilp3`} title={getLabel(22014, '安装其他工具')} showGroup={true}>
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@11irv3`} columns={otherColumns} dataSource={otherPlugins} pagination={false} />
        </WeaSearchGroup>
        {isIE && (
          <div className="wea-plugin-chk-msg">
            <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@g9logj`} checked={isCheck} onChange={this.onChange}>
              {getLabel(22017, '每次进入系统时检测')}
            </Checkbox>
          </div>
        )}
        {isIE && (
          <div className="wea-plugin-tip-msg">
            <i className="icon-coms02-Warning-01" />
            <span style={{ marginLeft: '10px' }}>{getLabel(22016, '注意：安装完毕请重启计算机！')}</span>
          </div>
        )}
      </div>
    );

    if (test) {
      columns = [
        {
          key: 'index',
          title: getLabel(15486, '序号'),
          dataIndex: 'index',
          width: '10%',
          render: (text, record) => parseInt(record.index) - 1,
        },
        { key: 'name', title: getLabel(195, '名称'), dataIndex: 'name', width: '15%' },
        { key: 'clsid', title: getLabel(22037, '控件') + getLabel(714, '编号'), dataIndex: 'clsid', width: '20%' },
        { key: 'clsname', title: getLabel(22037, '控件') + getLabel(195, '名称'), dataIndex: 'clsname', width: '20%' },
        { key: 'version', title: getLabel(567, '版本'), dataIndex: 'version', width: '10%' },
        {
          key: 'status',
          title: getLabel(602, '状态'),
          dataIndex: 'status',
          width: '10%',
          render: (text, record) => this.getPluginStatus(record.progid),
        },
        {
          key: 'download',
          title: getLabel(22011, '检测'),
          dataIndex: 'download',
          width: '15%',
          render: (text, record) => (
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@697817`} type="ghost" icon="search" onClick={() => this.onTest(record)}>
              {getLabel(22011, '检测')}
            </Button>
          ),
        },
      ];

      Content = (
        <div className="wea-plugin-body">
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@6jnsc2`} title={getLabel(22006, '控件检测')} showGroup={true}>
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@gt14uz`} columns={columns} dataSource={plugins.slice(1)} pagination={false} />
          </WeaSearchGroup>
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0thqcu`} title={getLabel(22019, '如果控件不能够正常运行怎么办？')} showGroup={true}>
            <div className="wea-plugin-step">
              <div className="wea-plugin-step-num">1</div>
              <span>
                {getLabel(22020, '第一步：')}
                {getLabel(83838, '从')} C:\WINDOWS\Downloaded Program Files {getLabel(22024, '删除通过自动提示安装方式注册的控件，对应名称参见clsname列；')}
              </span>
            </div>
            <div className="wea-plugin-step">
              <div className="wea-plugin-step-num">2</div>
              <span>
                {getLabel(22021, '第二步：')}
                {getLabel(22025, '从“控制面板 -> 删除或添加程序”删除通过下载控件方式安装的控件；')}
              </span>
            </div>
            <div className="wea-plugin-step">
              <div className="wea-plugin-step-num">3</div>
              <span>
                {getLabel(22022, '第三步：')}
                {getLabel(22026, '删除用手工方式注册的控件：')}
              </span>
              <div style={{ paddingLeft: '30px', color: '#666' }}>
                <p>1、{getLabel(22027, '在命令行执行')} regedit.exe；</p>
                <p>
                  2、{getLabel(22028, '在键 HKEY_CLASSES_ROOT\\CLSID 下查找对应的 clsid，如Office 控件的注册项为')} {'{23739A7E-5741-4D1C-88D5-D50B18F7C347}'}；
                </p>
                <p>
                  3、{getLabel(22029, '如果找到该注册项，表明控件已安装。安装的文件路径见 InprocServer32 项的值，')}
                  {getLabel(22027, '在命令行执行')}“regsvr32 /u &lt;{getLabel(22030, '带路径的文件名称')}&gt;”{getLabel(22031, '即可删除')}
                </p>
              </div>
            </div>
            <div className="wea-plugin-step">
              <div className="wea-plugin-step-num">4</div>
              <span>
                {getLabel(22023, '第四步：')}
                {getLabel(22032, '重新下载控件方式安装控件！')}
              </span>
            </div>
          </WeaSearchGroup>
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wzu5n2`} title={getLabel(22033, '为什么通过下载插件安装方式卸载控件会报错？')} showGroup={true}>
            <div>
              <span>{getLabel(22034, '卸载控件之前需要关闭所有 IE 窗口和使用控件的程序。')}</span>
            </div>
          </WeaSearchGroup>
        </div>
      );
    }

    if (display == 'page') {
      return (
        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@d7oasy`}
          loading={loading}
          title={getLabel(83543, '插件下载')}
          icon={<i className="icon-coms02-Plug-in" />}
          iconBgcolor="#a7adb5"
          buttons={this.getButtons(display)}
        >
          {Content}
        </WeaTop>
      );
    }

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zyk0dk`}
        visible={visible}
        loading={loading}
        title={getLabel(83543, '插件下载')}
        icon="icon-coms02-Plug-in"
        iconBgcolor="#a7adb5"
        style={{ width: 810, height: 480 }}
        zIndex={100}
        hasScroll={true}
        maskClosable={true}
        buttons={this.getButtons()}
        onCancel={this.onCancel}
      >
        {Content}
      </WeaDialog>
    );
  }

  getButtons = (display) => {
    const buttons = [];
    if (this.state.test) {
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bub67g`} type="primary" onClick={() => this.setState({ test: false })}>
          {getLabel(1290, '返回')}
        </Button>,
      );
    } else if (isIE) {
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p3b2ew`} type="primary" onClick={() => this.setState({ test: true })}>
          {getLabel(22006, '控件检测')}
        </Button>,
      );
    } else if (display != 'page') {
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@89ou00`} type="primary" onClick={this.onCancel}>
          {getLabel(83446, '确定')}
        </Button>,
      );
    }
    return buttons;
  };

  getPlugins = () => {
    this.setState({ loading: true });
    WeaTools.callApi('/api/portal/systemInfo/getPlugins', 'GET').then((result) => {
      const { data = {} } = result;
      this.setState({ loading: false, isCheck: data.isCheck, data });
    });
  };

  onChange = (e) => {
    const checked = e.target.checked;
    this.setState({ isCheck: checked });
    WeaTools.callApi('/api/portal/systemInfo/setIsCheck', 'POST', { isCheck: checked ? '0' : '1' });
  };

  getPluginStatus = (progid) => {
    if (!isIE) {
      return <i className="icon-coms-Prompt" style={{ color: '#fa0', fontSize: '14px' }} title={getLabel(507433, '非IE浏览器无需安装')} />;
    }

    let status = false;
    try {
      if (progid) {
        const obj = new ActiveXObject(progid);
        if (obj) {
          status = true;
        }
      } else {
        const obj1 = new ActiveXObject('iWebOffice2003.iWebOffice');
        const obj2 = new ActiveXObject('CHINAEXCELWEB.FormvwCtrl.1');
        if (obj1 && obj2) {
          status = true;
        }
      }
    } catch (e) {}

    return status ? (
      <i className="icon-coms-Upload-successfully-o" style={{ color: '#70d256', fontSize: '14px' }} />
    ) : (
      <i className="icon-coms-Clear" style={{ color: '#ff3f00', fontSize: '14px' }} />
    );
  };

  onTest = (obj) => {
    const dialog = new window.Dialog();
    dialog.currentWindow = window;
    dialog.Width = 650;
    dialog.Height = 400;
    dialog.Title = `${getLabel(22006, '控件检测')}: ${obj.name}`;
    dialog.URL = obj.checkpageurl;
    dialog.show();
  };

  onCancel = () => {
    this.props.onShow(false);
  };
}

export default WeaPlugin;
